package game.clock;

public abstract class Clock extends Thread {

	private boolean running;
	private long delay;
	
	public Clock(int delay) {
		this.delay = delay;
		this.running = true;
	}

	@Override
	public void run() {

		long waitForTick=0;

		long nextTick = System.currentTimeMillis() + delay;
		
		while (this.running) {
			waitForTick = nextTick - System.currentTimeMillis();
			/* Wait at least as long as delay, limiting the "ticks per second". */
			if (waitForTick > 0) {
				try {
					sleep(waitForTick);
				} catch (InterruptedException e) {
					System.err.println("Clock has been interrupted! Closing down ...");
					System.exit(-1);
				}
			}
			nextTick += delay;
			this.tick();
		}
	}

	public void halt() {
		this.running = false;
	}

	public int getFPS() {
		return (int) (1000/delay);
	}
	
	public abstract void tick();

}
